var isloginAlert = false;
(function($) {
    $.ajaxSetup({
        beforeSend: function(xhr) {
            xhr.setRequestHeader("AJAX", true);
        },
        error: function(xhr, status, err) {

            if (xhr.status == 401) {
                alert("401");
            } else if (xhr.status == 403) {
            	
            	if(!isloginAlert){
            		isloginAlert = true;
	                alert("사용자 세션이 만료되었습니다.\n 다시 로그인해주세요.");
	                location.href="/lg/loginForm.do";
	            }
                
            } else {
                //alert("예외가 발생했습니다. 관리자에게 문의하세요.");
            }
        }
    });
})(jQuery);

//숫자 타입에서 쓸 수 있도록 format() 함수 추가
Number.prototype.addComma = function(){
	
    if(this==0) return 0;
 
    var reg = /(^[+-]?\d+)(\d{3})/;
    var n = (this + '');
 
    while (reg.test(n)) n = n.replace(reg, '$1' + ',' + '$2');
 
    return n;
};
 
// 문자열 타입에서 쓸 수 있도록 format() 함수 추가
String.prototype.addComma = function(){
	
    var num = parseFloat(this);
    if( isNaN(num) ) return displayNull();
   
    return num.addComma();
};


//한국 요일 표시 0 : 월 ~ 6 : 일요일
Number.prototype.koreaWeekDay = function(){
	var koreaWeekDays = ['월', '화', '수', '목', '금', '토', '일'];
	var weekIndex = this;
	
	if(0 <= weekIndex && 6>= weekIndex){
		return koreaWeekDays[weekIndex];
	}else{
		return '';
	}	
}

// 한국 요일 표시 0 : 월 ~ 6 : 일요일
String.prototype.koreaWeekDay = function(){
	var koreaWeekDays = ['월', '화', '수', '목', '금', '토', '일'];
	var weekIndex = parseInt(this);
	
	if(0 <= weekIndex && 6>= weekIndex){
		return koreaWeekDays[weekIndex];
	}else{
		return '';
	}	
}

//문자열에서 str1을 str2치환
String.prototype.replaceAll = function (str1,str2){
	var str    = this;    
	var result   = str.replace(eval("/\\"+str1+"/g"),str2);
	return result;
	
};

//문자열에서 str1을 추가한 날짜포맷으로 변경.
String.prototype.DateFormat = function (str1){
	var str= this;
	if(str.length == 8){
		str = str.substring(0,4) + str1
		     +str.substring(4,6) + str1
		     +str.substring(6,8);
		
	}else if(str.length == 6){
		str = str.substring(0,4) + str1
	     +str.substring(4,6);;
	}
	
	return str;
};

//Date Format
Date.prototype.format = function(f) {
 if (!this.valueOf()) return " ";

 var weekName = ["일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"];
 var d = this;
  
 return f.replace(/(yyyy|yy|MM|dd|E|hh|mm|ss|a\/p)/gi, function($1) {
     switch ($1) {
         case "yyyy": return d.getFullYear();
         case "yy": return (d.getFullYear() % 1000).zf(2);
         case "MM": return (d.getMonth() + 1).zf(2);
         case "dd": return d.getDate().zf(2);
         case "E": return weekName[d.getDay()];
         case "HH": return d.getHours().zf(2);
         case "hh": return ((h = d.getHours() % 12) ? h : 12).zf(2);
         case "mm": return d.getMinutes().zf(2);
         case "ss": return d.getSeconds().zf(2);
         case "a/p": return d.getHours() < 12 ? "오전" : "오후";
         default: return $1;
     }
 });
};

String.prototype.string = function(len){var s = '', i = 0; while (i++ < len) { s += this; } return s;};
String.prototype.zf = function(len){return "0".string(len - this.length) + this;};
Number.prototype.zf = function(len){return this.toString().zf(len);};
// IE 8 forEach
if ('function' !== typeof Array.prototype.forEach) {
	Array.prototype.forEach = function(fn, scope) {
		for(var i = 0, len = this.length; i < len; ++i) {
			fn.call(scope, this[i], i, this);
	    }
	};
}
//IE 8 trim 
if ('function' !== typeof String.prototype.trim) {
	String.prototype.trim = function() {
		return this.replace(/^\s+|\s+$/g, ''); 
	}
}
//IE 8 indexOf 
if ('function' !== typeof Array.prototype.indexOf) {
	Array.prototype.indexOf = function(elt /*, from*/)
	{
	  var len = this.length >>> 0;
	
	  var from = Number(arguments[1]) || 0;
	  from = (from < 0)
	       ? Math.ceil(from)
	       : Math.floor(from);
	  if (from < 0)
	    from += len;
	
	  for (; from < len; from++)
	  {
	    if (from in this &&
	        this[from] === elt)
	      return from;
	  }
	  return -1;
	};
}
if ('function' !== typeof Array.prototype.reduce) {
	Array.prototype.reduce = function(callback, opt_initialValue){
	    'use strict';
	    if (null === this || 'undefined' === typeof this) {
	      // At the moment all modern browsers, that support strict mode, have
	      // native implementation of Array.prototype.reduce. For instance, IE8
	      // does not support strict mode, so this check is actually useless.
	      throw new TypeError(
	          'Array.prototype.reduce called on null or undefined');
	    }
	    if ('function' !== typeof callback) {
	      throw new TypeError(callback + ' is not a function');
	    }
	    var index, value,
	        length = this.length >>> 0,
	        isValueSet = false;
	    if (1 < arguments.length) {
	      value = opt_initialValue;
	      isValueSet = true;
	    }
	    for (index = 0; length > index; ++index) {
	      if (this.hasOwnProperty(index)) {
	        if (isValueSet) {
	          value = callback(value, this[index], index, this);
	        }
	        else {
	          value = this[index];
	          isValueSet = true;
	        }
	      }
	    }
	    if (!isValueSet) {
	      throw new TypeError('Reduce of empty array with no initial value');
	    }
	    return value;
  };
}
//공통코드 조회
function fnGetCommonData(pUrl, obj, pData, chkData, callBack){
	
	$.ajax({
	    url : pUrl,
	    type : "POST",
	    dataType : "json",
	    data : {"tab_id" : pData}, 
	    success: function(data) {
	    	
	    	obj.find("option").remove();
	    	
	    	var isChecked = "";
	    	if(chkData != "")isChecked = "checked";
	    	
	    	var len = data.retList.length;
	    	for(var i=0; i<len; i++){
	    		if(data.retList[i].tab_id != '11115'){
	    			obj.append("<option value=\""+data.retList[i].convert_id+" "+isChecked+"\">"+data.retList[i].tab_name+"</option>");
	    		}
	    		
	    	}
	    	
	    	$("#selUnit").selectbox("detach");
	    	$("#selUnit").selectbox("attach");
	    	
	    	if(typeof callBack == 'function'){
	    		callBack.call(this);
	    	}
	    }
	});
}

//날짜 계산
function fnGetDate(s, i){
	var dateSplit = s.split('-');
	var newDt = new Date(dateSplit[0], dateSplit[1], dateSplit[2]);
	newDt.setDate( newDt.getDate() + i );
	return converDateString(newDt);
}

function converDateString(dt){
	return dt.getFullYear() + "-" + addZero(eval(dt.getMonth())) + "-" + addZero(dt.getDate());
}

function addZero(i){
	var rtn = i + 100;
	return rtn.toString().substring(1,3);
}

//날짜 계산
function fnGetDateM(s, i){
	var newDt = new Date(Date.UTC(s.split('-')[0],s.split('-')[1],s.split('-')[2]));
	
	newDt.setMonth( newDt.getMonth() + i );
	
	return converDateStringM(newDt);
}


function converDateStringM(dt){
	return dt.getFullYear() + "-" + addZero(eval(dt.getMonth()+1));
}

function addZero(i){
	var rtn = i + 100;
	return rtn.toString().substring(1,3);
}



//null 일때 표시하는 문자
function displayNull(){
	return "-";
}

function displayNullValue(obj){
	return (obj  == null ? displayNull() : obj);
	
}

// 숫자만 입력 
function isNum(obj){ 
	var word = obj.value;
	var str = "1234567890";
	for(i=0; i<word.length; i++){
		if(str.indexOf(word.charAt(i))< 0){
			alert("숫자만 입력 가능합니다.");
			obj.value="";
			obj.focus();
			return false;
			
		}
		
	}
	
}

// json to param str;
parseJsonStr = function(_params){
	var paramsStr = '';
	for(_key in _params){
		if('' != paramsStr){
			paramsStr += '&';
		}
		paramsStr += _key + '=' +_params[_key];
	}
	return paramsStr;
}



/**
 * DataTable PDF download
 */
TableTools.BUTTONS.user_pdf = $.extend( true, TableTools.buttonBase, {
	"sButtonText": "PDF",
	"fnClick": function( nButton, oConfig) {
		var _pdfDataTableData =  $('#' + $(nButton).parent().parent().find('table').attr('id')).dataTable().fnGetNodes();
		var _theadStr = $($('#' + $(nButton).parent().parent().find('table').attr('id'))).find('thead').html().replaceAll('<tr', '<tr bgcolor="#dddddd" border="1"');
		_theadStr = _theadStr.replaceAll('<th', '<th border="1"');
		
		var _tbodyStr = '';
		var _dataTableHtml = ''
		for(var _dtdataCnt = 0 ; _dtdataCnt < _pdfDataTableData.length; _dtdataCnt++){
			_tbodyStr += '<tr border="1">' + $(_pdfDataTableData[_dtdataCnt]).html() + '</tr>';
		}
		_tbodyStr = _tbodyStr.replace(/\<a.*\)\>/gi, '').replace(/\<\/a\>/gi, '');
		_dataTableHtml = '<table><thead>' + _theadStr + '</thead><tbody>' + _tbodyStr +'</tbody></table>';
		var _pdfdowndform = document.createElement('form');
		_pdfdowndform.setAttribute('action', '/datatable/ajax/selectDatatableToPdf.do');
		_pdfdowndform.setAttribute('method', 'POST');
		
		var _pdfinputdata = document.createElement('input');
		_pdfinputdata.setAttribute('type', 'hidden');
		_pdfinputdata.setAttribute('name', '_tableData');
		_pdfinputdata.setAttribute('value', _dataTableHtml);
		
		_pdfdowndform.appendChild(_pdfinputdata);
		
		_pdfdowndform.submit();
	}
} );

